<template>
  <div class="container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>{{ isAdd ? '试题录入' : '试题修改' }}</span>
      </div>
      <!-- card body -->
      <el-form :model="form" ref="form" :rules="formRule" label-width="80px" :inline="false" size="normal">
        <el-form-item label="学科" prop="subjectID">
          <el-select v-model="form.subjectID" placeholder="请选择" filterable @change="subjectChange" ref="select">
            <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="form.catalogID" placeholder="请选择" filterable>
            <el-option v-for="item in directorysList" :key="item.id" :label="item.directoryName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择" filterable>
            <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市" class="citys" prop="city">
          <el-select v-model="form.province" placeholder="请选择" filterable @change="cityChange" class="city">
            <el-option v-for="item in provinces" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-select v-model="form.city" placeholder="请选择" filterable class="city">
            <el-option v-for="item in cityList" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="方向" prop="direction">
          <el-select v-model="form.direction" placeholder="请选择" filterable>
            <el-option v-for="(item, index) in direction" :key="index" :label="item" :value="item"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="form.questionType">
            <el-radio :label="item.value + ''" v-for="(item, index) in questionType" :key="index">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio :label="item.value + ''" v-for="(item, index) in difficulty" :key="index">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题干" prop="question">
          <quill-editor v-model="form.question" />
        </el-form-item>

        <el-form-item label="选项" v-if="form.questionType == 1" class="item">
          <p v-for="(item, index) in form.options" :key="index">
            <el-radio v-model="radio" :label="item.code"></el-radio>
            <el-input v-model="item.title" size="normal"></el-input>
            <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="(response, file) => handleAvatarSuccess(response, file, item)">
              <img v-if="item.img" :src="item.img" class="avatar" />
              <i v-else class="avatar-upload">上传图片</i>
            </el-upload>
          </p>
        </el-form-item>

        <el-form-item label="选项" v-if="form.questionType == 2" class="item">
          <p v-for="(item, index) in form.options" :key="index">
            <el-checkbox v-model="item.isRight" :label="item.code"></el-checkbox>
            <el-input v-model="item.title" size="normal"></el-input>
            <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="(response, file) => handleAvatarSuccess(response, file, item)">
              <img v-if="item.img" :src="item.img" class="avatar" />
              <i v-else class="avatar-upload">上传图片</i>
            </el-upload>
          </p>
        </el-form-item>

        <el-form-item label="" size="normal">
          <el-button type="danger" size="default" :disabled="form.questionType == 1" v-if="form.questionType !== 3" @click="btnAddQuestion">+增加选项与答案</el-button>
        </el-form-item>

        <el-form-item label="解析视频">
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>

        <el-form-item label="答案解析" prop="answer">
          <quill-editor v-model="form.answer" />
        </el-form-item>

        <el-form-item label="题目备注">
          <el-input v-model="form.remarks" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" class="pz"></el-input>
        </el-form-item>

        <el-form-item label="试题标签">
          <el-select v-model="form.tags" placeholder="请选择试题标签">
            <el-option v-for="item in tagsList" :key="item.id" :label="item.tagName" :value="item.id + ''"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" v-if="isAdd" @click="submit">确认提交</el-button>
          <el-button type="success" v-else @click="submit">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
let arr = []
for (var i = 65; i < 91; i++) {
  arr.push(String.fromCharCode(i))
}
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { list as companylist } from '@/api/hmmm/companys.js'
import { list as tagslist } from '@/api/hmmm/tags.js'
import { list as directoryslist } from '@/api/hmmm/directorys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { detail, add, update } from '@/api/hmmm/questions.js'
import { mapState } from 'vuex'
import { questionType, direction, difficulty } from '@/api/hmmm/constants.js'
export default {
  data() {
    return {
      // 当前的状态是否是添加
      isAdd: true,
      // 表单信息
      form: {
        subjectID: '',
        difficulty: '1',
        questionType: '1',
        tags: '',
        province: '',
        city: '',
        direction: '',
        catalogID: '',
        enterpriseID: '',
        question: '',
        options: [
          {
            code: 'A',
            title: '',
            img: null,
            isRight: false
          },
          {
            title: '',
            img: null,
            isRight: false,
            code: 'B'
          },
          {
            title: '',
            img: null,
            code: 'C',
            isRight: false
          },
          {
            title: '',
            img: null,
            code: 'D',
            isRight: false
          }
        ],
        videoURL: '',
        answer: ''
      },
      // 表单校验对象
      formRule: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]
      },
      // 二级目录列表
      directorysList: [],
      // 标签数据
      tagsList: [],
      // 试题类型
      questionType,
      // 难度
      difficulty,
      // 方向
      direction,
      // 城市列表
      cityList: [],
      // 一级城市
      city: '',
      // 单选按钮
      radio: '',
      // 多选按钮
      checkedList: [],
      // 企业列表数据
      companyList: [],
      imageUrl: ''
    }
  },
  components: {
    quillEditor
  },

  computed: {
    ...mapState({
      subjectList: state => state.subject.subjectList,
      userList: state => state.subject.userList
    }),
    // 城市数据
    provinces
  },
  created() {
    this.subjectList || this.$store.dispatch('getSubject', { pagesize: 1000 })
    this.userList || this.$store.dispatch('getUser', { pagesize: 1000 })
    this.getCompanyList()
    if (this.$route.query.id) {
      this.isAdd = false
      this.getDetail()
    }
  },
  mounted() {},
  methods: {
    // 学科变化
    async subjectChange(val) {
      console.log(val)

      // 获取二级目录列表
      let { data: res } = await directoryslist({
        subjectID: val,
        pagesize: 100
      })
      console.log(1111)
      this.directorysList = res.items
      // 获取标签列表
      let { data: result } = await tagslist({
        subjectID: val,
        pagesize: 100
      })

      this.tagsList = result.items
    },
    // 城市变化
    cityChange(val) {
      this.cityList = citys(val)
    },
    // 获取企业列表数据
    async getCompanyList() {
      let { data: res } = await companylist({
        pagesize: 1000
      })
      console.log(res)
      this.companyList = res.items
    },
    // 获取当前数据的方法
    async getDetail() {
      let { data: res } = await detail({
        id: this.$route.query.id
      })
      res.options.forEach(item => {
        item.isRight = Boolean(item.isRight)
        if (res.questionType == 1 && item.isRight) {
          this.radio = item.code
        }
      })
      let arr = res.options
      for (let i = 0; i < arr.length - 1; i++) {
        //冒泡趟数
        for (let j = 0; j < arr.length - i - 1; j++) {
          if (arr[j + 1].code < arr[j].code) {
            let temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp
          }
        }
      }

      console.log(arr)
      this.form = res
      this.subjectChange(this.form.subjectID)
    },
    // 添加按钮事件
    btnAddQuestion() {
      let obj = {
        code: arr[this.form.options.length],
        img: '',
        isRight: 0,
        title: ''
      }
      this.form.options.push(obj)
    },
    // 上传成功的函数
    handleAvatarSuccess(res, file, item) {
      item.img = URL.createObjectURL(file.raw)
    },
    // 添加或者修改提交事件
    submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 对数据进行处理
          if (this.form.questionType == 1) {
            this.form.options.forEach(item => {
              if (item.code == this.radio) {
                item.isRight = true
              } else {
                item.isRight = false
              }
            })
          }

          // 判断当前状态
          if (this.isAdd) {
            await add(this.form)
            this.$message.success('添加成功')
          } else {
            await update(this.form)
            this.$message.success('修改成功')
          }
          this.$router.replace('/questions/list')
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.ql-container {
  min-height: 300px !important;
}

.el-select {
  width: 400px;
  height: 35px;
}
.item .el-input {
  width: 240px;
  height: 35px;
}
.pz {
  width: 400px;
}
.city {
  width: 198px;
}
.el-checkbox {
  margin-right: 30px;
}

::v-deep .avatar-uploader,
.el-upload {
  margin-left: 5px;
  width: 100px;
  height: 60px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: inline-block;
  vertical-align: middle;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .el-upload.el-upload--text {
  font-size: 16px;
  font-style: normal;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
